from google.appengine.api import memcache
from libs import simplejson as json, utils
from app import abstract, models, config
import sys, logging
from time import time
        
class Action(abstract.Action):
    
    result = None
    
    failure = False
    
    check_oauth = True
    
    platform_id = 0
    
    def initialize(self, request, response):
        self.request = request
        self.response = response
        self.setup()
    
    def setup(self):
        
        self.owner_id = self.request.get("opensocial_owner_id")
        self.viewer_id = self.request.get("opensocial_viewer_id")
        
        self.result = Result(self.response)
        
        # check user ####
        if self.viewer_id != "":
            user = models.user.getById(self.viewer_id)
            if user == None: 
                user = models.user.create(self.viewer_id)
                self.result.user_id = utils.id2ids(self.viewer_id)
            else:
                self.result.user_id = utils.id2ids(user.key().id())
        
        self.platform_id = utils.getPlatformID(self.viewer_id)
        
        self.result.nonce = self.request.get("oauth_nonce")
        self.result.platform_id = self.platform_id
        
        #### security checks ######

        if not config.PRODUCTION_MODE or not self.check_oauth: return
        
        if self.param('oauth_nonce') == ""  or self.param('oauth_signature') == ""  or self.param('oauth_timestamp') == "":
            self.result.status = 403
            self.failure = True
            
        if self.param('oauth_timestamp', "int") < (time() - 600):
            self.result.status = 403
            self.failure = True
            
        if not memcache.add(key="oa/nc/" + self.param('oauth_nonce'), value=1, time=600): 
            self.result.status = 403
            self.failure = True
        
    def post(self):
        
        if self.failure:
            self.result.send(False)
            return
        
        data = self._post()
        
        self.result.send(data)
        
    def get(self):
        
        if self.failure:
            self.result.send(False)
            return
        
        data = self._get()
        
        self.result.send(data)

class Result():
    
    status = 200
    
    nonce = ""
    
    data = None
    
    response = None
    
    sent = False
    
    user_id = None
    
    def __init__(self, response):
        self.response = response
    
    def send(self, data, more = None):
        
        if self.sent: return
        self.sent = True
        
        if more == None:
            msg = {"message" : 
                    { "meta" : 
                     {"nonce": self.nonce, 
                      "status" : self.status,
                      "uid" : self.user_id,
                      "platform" : self.platform_id
                     }, 
                      "data" : data}}
        else:
            msg = {"message"  : 
                    { "meta"  : 
                     {"nonce" :  self.nonce, 
                      "status": self.status,
                      "uid" : self.user_id,
                      "platform" : self.platform_id,
                      "count" : len(data),
                      "more"  : more
                     }, 
                      "data"  : data}}
            
        self.response.set_status(self.status) 
        self.response.headers['Content-Type'] = 'application/json'
        self.response.out.write(json.dumps(msg))